<template>
	<view class="container">
		<!-- 商家信息 -->
		<view class="merchant-info" v-if="venue && venue.name">
			<text class="merchant-name">商家名称: {{ venue.name }}</text>
			<text class="merchant-address">商家地址: {{ venue.address }}</text>
			<text class="merchant-contact">联系电话: {{ venue.phone }}</text>
			<text class="merchant-hours">营业时间: {{ venue.businessHours }}</text>
			
			  <!-- 添加联系商家的按钮 -->
			  <button class="contact-button" @click="contactMerchant">联系商家</button>
		</view>

		<!-- 球场列表 -->
		<view class="venue-list" v-if="courts && courts.length > 0">
			<view v-for="(court, index) in courts" :key="index" class="venue-card">
				<image :src="`http://localhost:8080${court.imageUrl}`" class="venue-image" />
				<view class="venue-content">
					<text class="venue-name">球场名称: {{ court.name }}</text>
					<!-- <text class="venue-address">球场地址: {{ court.address }}</text> -->
					<!-- <text class="venue-hours">营业时间: {{ court.businessHours }}</text> -->

					<!-- 预约按钮 -->
					<view class="appointment">
						<!-- 	<text>Booking Status: {{ court.bookingStatus }}</text>
						<text>Number: {{  court.number }}</text> -->
						<view v-if="court.bookingStatus == '1' && court.number < 15 && court.userBooked == false">

							<button class="book-button" @click="showDialog(court)">
								预约
							</button>
						</view>
						<!-- 判断是否已经预约 -->
						<text v-else-if="court.userBooked" class="status-text">您已经预约</text>
						<text v-else-if="court.number >= 15" class="status-text">已约满</text>
						<text v-else class="status-text">已被预约</text>
					</view>


				</view>
			</view>
		</view>

		<!-- 预约弹框 -->
		<view v-if="showDialogBox" class="dialog-overlay" @click="closeDialog">
			<view class="dialog" @click.stop>

				<!-- 定场方式下拉框 -->
				<view class="form-group">
					<label for="bookingMethod">定场方式:</label>
					<select v-model="bookingDetails.bookingMethod" class="select-dropdown" @change="updateAmount">
						<option value="1">个人</option>
						<option value="0">包场</option>
					</select>
				</view>

				<!-- 订单状态 -->
				<view class="form-group">
					<label for="orderStatus">订单状态:</label>
					<text>{{ bookingDetails.orderStatus }}</text> <!-- 默认“待确认” -->
				</view>

				<!-- 支付状态 -->
				<view class="form-group">
					<label for="paymentStatus">支付状态:</label>
					<text>{{ bookingDetails.paymentStatus === 0 ? '未支付' : '已支付' }}</text>
				</view>

				<!-- 金额 -->
				<view class="form-group">
					<label for="amount">金额:</label>
					<input type="number" v-model="bookingDetails.amount" :disabled="true" class="disabled-input"
						:value="bookingDetails.amount" />
				</view>

				<!-- 预定时间 -->
				<TimePicker @modelValue="test" />

				<!-- 备注信息 -->
				<view class="form-group">
					<label for="remarks">备注信息:</label>
					<input type="text" v-model="bookingDetails.remarks" class="input-field" />
				</view>

				<view class="dialog-actions">
					<button class="cancel-button" @click="closeDialog">取消</button>
					<button class="confirm-button" @click="handleAppointment">确认预约</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getStadiumList,
		isReservation, //判断是否预约过该球场
		insertBookings, //插入预约表
		insertOrder //插入订单
	} from '@/api/venue/venue.js'; // 获取场馆详情的接口
	import TimePicker from '@/component/TimePicker.vue';
	export default {
		data() {
			return {
				venue: {}, // 商家数据
				courts: [], // 场馆数据（初始化为空数组）
				showDialogBox: false, // 控制对话框显示
				currentCourt: null, // 当前选择的场馆d:,
				inputValue: '',
				orderId: '',
				userId: this.$store.state.user.userId,
				bookingDetails: {
					bookingMethod: '个人', // 默认选择个人
					amount: '', // 默认金额
					paymentStatus: 0, // 默认支付状态
					orderStatus: '待确认', // 默认订单状态
					bookingTime: '', // 默认预约时间
					remarks: '', // 备注信息
				},

			};
		},
		components: {
			TimePicker
		},
		onLoad(options) {
			if (options.venue) {
				this.venue = JSON.parse(decodeURIComponent(options.venue));
				console.log('接收到的商家信息:', this.venue);
			}
		},
		mounted() {
			this.fetchVenueDetail();
			console.log(this.userId);
		},
		methods: {
			test(value) {
				console.log(value);
				this.bookingDetails.bookingTime = value
			},
			
			// 联系商家
			  contactMerchant() {
			    // 这里可以是你打开商家的联系方式的操作
				uni.navigateTo({
					url: `/pages/message/chat?name=${this.venue.name}&avatar=${this.venue.imageUrl}&userId=${this.venue.id}`
				})
			  },

			// 获取商家及其所有场馆的详情
			fetchVenueDetail() {
				const merchantId = this.venue.userId;
				if (merchantId) {
					getStadiumList(merchantId)
						.then((res) => {
							// 确保返回数据是数组
							this.courts = Array.isArray(res.data) ? res.data : [];
							

							this.courts.forEach((court) => {
								isReservation(this.userId, court.id) // 调用查询预约状态的接口
									.then((res) => {
										// 根据返回的结果更新球场的预约状态
										// 动态添加 userBooked 属性
										this.$set(court, 'userBooked', res
										.data); // 假设返回的 res.data 是布尔值，表示是否预约
										console.log('场馆数据:', this.courts);
										console.log(court);
									})
									
									.catch((error) => {
										console.error('查询预约状态失败', error);
									});
							});

						})
						.catch((error) => {
							console.error('获取商家详情失败', error);
						});
				}
			},
			// 监听定场方式变化更新金额
			updateAmount() {
				if (this.bookingDetails.bookingMethod === '1') {
					// 个人，设置为单个场地价格
					this.bookingDetails.amount = this.currentCourt ? this.currentCourt.singlePrice : 100;
				} else if (this.bookingDetails.bookingMethod === '0') {
					// 包场，设置为固定包场金额
					this.bookingDetails.amount = 500;
				}
			},
			// 判断场馆是否可以预约
			// canBook(status) {
			// 	return status === 'AVAILABLE';
			// },
			// 显示预约对话框
			showDialog(court) {
				this.currentCourt = court; // 记录当前场馆
				console.log('当前预约的场馆编号', court);
				this.showDialogBox = true; // 显示对话框
			},
			// 关闭预约对话框
			closeDialog() {
				this.showDialogBox = false; // 隐藏对话框
				this.currentCourt = null; // 清除当前场馆
			},


			// 处理预约操作
			handleAppointment() {
				// 准备插入预约表的信息
				const bookings = {
					merchantId: this.venue.id, // 商家id
					courtId: this.currentCourt.id, // 球场id
					bookingTime: this.bookingDetails.bookingTime, // 预约时间
					status: 1, // 预约状态
				};


				// 预约成功后，准备插入订单信息
				const bookingData = {
					merchantId: this.venue.id, // 商家id
					courtId: this.currentCourt.id, // 场馆id
					reservationType: this.bookingDetails.bookingMethod, // 定场方式（个人/包场）
					totalAmount: this.bookingDetails.amount, // 金额
					paymentStatus: this.bookingDetails.paymentStatus, // 支付状态
					reservationTime: this.bookingDetails.bookingTime, // 预约时间
					remarks: this.bookingDetails.remarks, // 备注信息
				};
				
				// 将需要传递的参数转化为 URL 查询参数
				const venueStr = encodeURIComponent(JSON.stringify(this.venue));
				const courtsStr = encodeURIComponent(JSON.stringify(this.currentCourt));
				const bookingDataStr = encodeURIComponent(JSON.stringify(bookingData));

				// 调用插入预约信息的接口
				insertBookings(bookings)
					.then(res => {
						console.log('预约成功:', res);
						console.log('参数',bookingData);
						// 调用插入订单信息的接口
						insertOrder(bookingData)
							.then((res) => {
								this.orderId = res.data;
								const orderId = this.orderId;
								// 跳转到支付页面，传递查询参数
								uni.navigateTo({
									url: `/pages/stadium/payment?venue=${venueStr}&courts=${courtsStr}&bookingData=${bookingDataStr}&orderId=${orderId}`
								});
								this.closeDialog(); // 关闭对话框
							})
							.catch((error) => {
								console.error('插入订单失败', error);
								alert('订单创建失败，请稍后重试');
							});
					})
					.catch((error) => {
						console.error('预约失败', error);
						alert('预约失败，请稍后重试');
					});
				this.closeDialog(); // 关闭对话框
			},

		},
	};
</script>

<style scoped>
	/* 商家信息样式 */
	.merchant-info {
		margin-bottom: 30px;
		padding: 20px;
		background-color: #fff;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.merchant-info text {
		display: block;
		margin-bottom: 10px;
		font-size: 16px;
	}

	.merchant-info .merchant-name {
		font-weight: bold;
	}

	/* 场馆列表样式 */
	.venue-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20px;
		justify-content: center;
	}

	.venue-card {
		width: 320px;
		background-color: #fff;
		border-radius: 10px;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
		padding: 20px;
		transition: transform 0.3s ease, box-shadow 0.3s ease;
	}

	.venue-card:hover {
		transform: translateY(-5px);
		box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
	}

	.venue-image {
		width: 100%;
		height: 160px;
		object-fit: cover;
		border-radius: 8px;
	}

	.venue-content {
		margin-top: 10px;
	}

	.venue-name,
	.venue-address,
	.venue-hours {
		font-size: 14px;
		/* margin-bottom: 10px; */
		display: block;
		/* 确保每个字段单独一行 */
	}

	.booking-status {
		font-size: 14px;
		color: #f44336;
		margin-bottom: 15px;
	}

	.appointment .book-button {
		width: 100%;
		padding: 12px;
		background-color: #4CAF50;
		color: white;
		border: none;
		border-radius: 5px;
		font-size: 16px;
		cursor: pointer;
	}

	.appointment .status-text {
		font-size: 16px;
		color: gray;
		color: #f44336;
	}

	/* 预约弹框样式 */
	/* 预约弹框样式调整 */
	.dialog-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.dialog {
		width: 90%;
		max-width: 400px;
		background-color: #fff;
		padding: 20px;
		border-radius: 10px;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
		position: relative;
		/* 使得 TimePicker 能在对话框内定位 */
		z-index: 2000;
		/* 保证对话框内容处于较高层级 */
	}

	.form-group {
		margin-bottom: 15px;
	}

	.form-group label {
		font-size: 16px;
		margin-bottom: 5px;
	}

	/* 定场方式下拉框更大 */
	.select-dropdown {
		width: 100%;
		padding: 12px;
		font-size: 16px;
		border: 1px solid #ccc;
		border-radius: 5px;
		background-color: #f9f9f9;
	}

	/* 预定时间和备注信息输入框 */
	.input-field {
		width: 365px;
		padding: 12px;
		border: 1px solid #ccc;
		border-radius: 5px;
		background-color: #f9f9f9;
		font-size: 16px;
		margin-bottom: 15px;
	}

	/* 禁止修改的输入框样式，支付状态和订单状态使用此样式 */
	.input-field[disabled] {
		width: 100%;
		padding: 10px;
		border: 1px solid #ccc;
		background-color: #f0f0f0;
		cursor: not-allowed;
	}

	.disabled-input {
		background-color: #f0f0f0;
		border: 1px solid #ccc;
		cursor: not-allowed;
	}

	.dialog-actions {
		display: flex;
		justify-content: space-between;
	}

	.dialog-actions button {
		padding: 10px;
		width: 48%;
		border-radius: 5px;
		font-size: 16px;
	}

	.cancel-button {
		background-color: #f44336;
		color: white;
	}

	.confirm-button {
		background-color: #4CAF50;
		color: white;
	}

	.error-message {
		color: red;
		font-size: 14px;
		margin-top: 5px;
	}

	/* 增加一个容器样式 */
	.time-picker-container {
		margin-top: 15px;
		/* 使时间选择器距离上方有间隔 */
		z-index: 9999;
		/* 确保它在对话框之上 */
		width: 100%;
	}
	
	/* 联系商家的按钮样式 */
	.contact-button {
	  width: 100%;
	  padding: 12px;
	  background-color: #007BFF;
	  color: white;
	  border: none;
	  border-radius: 5px;
	  font-size: 16px;
	  cursor: pointer;
	  margin-top: 20px;
	}

</style>